package youcaihuaoa.weetop.com.ui.apply

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.CustomProfileItemBean
import com.robot.base.model.MyApplyInfoBean
import com.robot.base.util.UriUtils
import youcaihuaoa.weetop.com.BR
import youcaihuaoa.weetop.com.R
import youcaihuaoa.weetop.com.databinding.AppActvityMyApplyProfileBinding
import youcaihuaoa.weetop.com.ui.adapter.*
import youcaihuaoa.weetop.com.vm.apply.MyApplyProfileViewModel
import java.io.File
import java.util.*

@Route(path = AppConstants.Router.Main.A_MY_APPLY_PROFILE)
class MyApplyProfileActivity :
    GLBaseActivity<AppActvityMyApplyProfileBinding, MyApplyProfileViewModel>() {

    var id = ""
    var title = ""
    var type = ""
    var status = 0


    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_actvity_my_apply_profile

    override fun initVariableId(): Int = BR.viewModel


    private lateinit var treeViewAdapter: TreeViewAdapter
    private lateinit var trendApplyProfileAdapter: TrendApplyProfileAdapter
    private lateinit var applyAdapter: MyApplyProfileAdapter
    private lateinit var folderInfoAdapter: FolderInfoAdapter
    private lateinit var myAppInfoAdapter: MyApplyInfoAdapter
    override fun initComponents() {
        addSingleTitleBar(title)
        treeViewAdapter = TreeViewAdapter(
        ).apply {
            setOnItemClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.iv_select -> {
                        treeViewAdapter.data[position].select =
                            !treeViewAdapter.data[position].select
                        treeViewAdapter.data[position].son_menu_data?.forEach { it1 ->
                            it1.select = treeViewAdapter.data[position].select
                            it1.son_menu_data?.forEach { it2 ->
                                it2.select = it1.select
                            }
                        }
                        treeViewAdapter.data[position].expanded =
                            treeViewAdapter.data[position].select
                    }
                    else -> {
                        treeViewAdapter.data[position].expanded =
                            !treeViewAdapter.data[position].expanded
                    }
                }

                treeViewAdapter.notifyItemChanged(position)
            }
        }
        applyAdapter = MyApplyProfileAdapter()
        trendApplyProfileAdapter = TrendApplyProfileAdapter()
        folderInfoAdapter = FolderInfoAdapter(status == 2)
        myAppInfoAdapter = MyApplyInfoAdapter().apply {
            setOnItemClickListener { adapter, view, position ->
                when (myAppInfoAdapter.data[position].type) {
                    "1" -> {
                        initCustomDate(position)
                    }
                    "1_time" -> {
                        initCustomTime(position)
                    }
                    "bk_type" -> {
                        initOptionsPicker(position)
                    }
                }
            }
        }
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@MyApplyProfileActivity)
            adapter = applyAdapter
        }

        binding.mRvOther.apply {
            layoutManager = LinearLayoutManager(this@MyApplyProfileActivity)
            adapter = trendApplyProfileAdapter
        }

        binding.mRvFolderInfo.apply {
            layoutManager = GridLayoutManager(this@MyApplyProfileActivity, 2)
            adapter = folderInfoAdapter
        }

        binding.mRvInfo.apply {
            layoutManager = LinearLayoutManager(this@MyApplyProfileActivity)
            adapter = myAppInfoAdapter
        }

        binding.mRvQx.apply {
            layoutManager = LinearLayoutManager(this@MyApplyProfileActivity)
            adapter = treeViewAdapter
        }
    }

    private fun initPermission() {
        XXPermissions.with(this)
            .permission(
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE
            )
            // 申请多个权限
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                    UriUtils.skipFile(this@MyApplyProfileActivity)
                }

                override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                    showToast("部分权限未授权，影响功能使用")
                }
            })
    }

    override fun initData() {
        viewModel.initData(status, id, type)
    }

    override fun initParam() {
        id = intent.getStringExtra(AppConstants.BundleKey.ID) ?: ""
        title = intent.getStringExtra(AppConstants.BundleKey.TITLE) ?: ""
        type = intent.getStringExtra(AppConstants.BundleKey.TYPE) ?: ""
        status = intent.getIntExtra(AppConstants.BundleKey.STATUS, 0)
    }

    override fun initViewObservable() {
        viewModel.uiEvent.menuDataLiveEvent.observe(this) {
            val examineData = it.examine_data
            applyAdapter.setNewInstance(examineData)
            val endBean = CustomProfileItemBean()
            endBean.title = "完成"
            applyAdapter.addData(endBean)
            trendApplyProfileAdapter.setNewInstance(it.str_data)
        }

        viewModel.uiEvent.infoEvent.observe(this) {
            folderInfoAdapter.status = (status == 2 || viewModel.complete.get() == true)
            myAppInfoAdapter.setNewInstance(it as MutableList<MyApplyInfoBean>?)
        }
        viewModel.uiEvent.updateFileEvent.observe(this) {
            folderInfoAdapter.addData(it)
        }
        viewModel.uiEvent.skipFileEvent.observe(this) {
            initPermission()
        }

        viewModel.uiEvent.qxDataEvent.observe(this) {
            val qxMenuData = viewModel.qx_menu_data.split(",")
            LogUtils.e(viewModel.complete.get())
            it.forEach { it1 ->
                if (it1.son_menu_data.isNullOrEmpty()) {
                    if (qxMenuData.contains(it1.id)) {
                        it1.select = true
                        it1.expanded = true
                    }
                }
                if (viewModel.complete.get() == true) {
                    it1.enable = false
                } else {
                    it1.enable = status != 2
                }
                it1.son_menu_data?.forEach { it2 ->
                    LogUtils.e(it2.son_menu_data.isNullOrEmpty(), it2.name)
                    if (it2.son_menu_data.isNullOrEmpty()) {
                        if (qxMenuData.contains(it2.id)) {
                            it2.select = true
                            it2.expanded = true
                            it1.select = true
                            it1.expanded = true
                        }
                    }
                    if (viewModel.complete.get() == true) {
                        it2.enable = false
                    } else {
                        it2.enable = status != 2
                    }
                    it2.son_menu_data?.forEach { it3 ->
                        if (qxMenuData.contains(it3.id)) {
                            it3.select = true
                            it2.select = true
                            it2.expanded = true
                            it1.select = true
                            it1.expanded = true
                        }
                        if (viewModel.complete.get() == true) {
                            it3.enable = false
                        } else {
                            it3.enable = status != 2
                        }
                    }
                }
            }
            treeViewAdapter.setList(it)
        }

        viewModel.uiEvent.confirmEvent.observe(this) {
            val mapList = mutableListOf<Map<String, String?>>()
            trendApplyProfileAdapter.data.forEach {
                if (!TextUtils.isEmpty(it.text)) {
                    val map = mapOf(
                        "title" to it.title,
                        "value" to it.text,
                        "status" to it.status
                    )
                    mapList.add(map)
                }
            }
            val jbcs_fj_path = StringBuffer()
            folderInfoAdapter.data.forEach {
                jbcs_fj_path.append(it.file_path).append(";")
            }
            LogUtils.e(jbcs_fj_path)
            if (jbcs_fj_path.isNotEmpty()) {
                jbcs_fj_path.deleteCharAt(jbcs_fj_path.length - 1)
            }
            val map = HashMap<String, Any>()
            if (!mapList.isNullOrEmpty()) {
                map["str_data"] = JSON.toJSONString(mapList)
            }

            if (jbcs_fj_path.isNotEmpty()) {
                map["public_annex_path"] = jbcs_fj_path
            }
            map["cz_type"] = if (viewModel.status.get() == 0) {
                "1"
            } else {
                "2"
            }
            if (viewModel.status.get() != 0) {
                map["id"] = viewModel.id
            }
            val qxStringBuffer = StringBuffer()
            treeViewAdapter.data.forEach {
                if (it.select) {
                    LogUtils.e(it.name, it.id, it.select, it.level, it.enable)
                    qxStringBuffer.append(it.id).append(",")
                }
                it.son_menu_data?.forEach { it1 ->
                    if (it1.select) {
                        LogUtils.e(it1.name, it1.id, it1.select, it1.level, it1.enable)
                        qxStringBuffer.append(it1.id).append(",")
                    }
                    it1.son_menu_data?.forEach { it2 ->
                        if (it2.select) {
                            LogUtils.e(it2.name, it2.id, it2.select, it2.level, it2.enable)
                            qxStringBuffer.append(it2.id).append(",")
                        }
                    }
                }
            }
            if (qxStringBuffer.isNotEmpty()) {
                qxStringBuffer.deleteCharAt(qxStringBuffer.length - 1)
                map["qx_menu_data"] = qxStringBuffer.toString()
                LogUtils.e(qxStringBuffer.toString())
            }
            myAppInfoAdapter.data.forEach {
                if (it.type != "bk_type") {
                    map[it.key] = it.text ?: ""
                } else {
                    map[it.key] = viewModel.bkType.indexOf(it.text) + 1
                }
            }
            viewModel.confirm(map)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val uri: Uri? = data!!.data
            if (uri != null) {
                if ("file".equals(uri.scheme, ignoreCase = true)) { //使用第三方应用打开
                    val path = uri.path
                    viewModel.uploadFile(File(path))
                    return
                }
                LogUtils.e(uri)
                val path = UriUtils.getPath(this, uri)
                LogUtils.e(path)
                viewModel.uploadFile(File(path))
            }
        }
    }

    private fun initCustomDate(adapterIndex: Int) {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        val selectedDate = Calendar.getInstance() //系统当前时间
        val startDate = Calendar.getInstance()
        startDate[1900, 0] = 1
        val endDate = Calendar.getInstance()
        endDate.add(Calendar.YEAR, +5)
//        endDate[2100, 2] = 28
        //时间选择器 ，自定义布局
        val pvCustomTime = TimePickerBuilder(
            this
        ) { date, v -> //选中事件回调
            val time = TimeUtils.date2String(date, "yyyy-MM-dd")
            myAppInfoAdapter.data[adapterIndex].text = time
            myAppInfoAdapter.notifyItemChanged(adapterIndex)
        }
            .setDate(selectedDate)
            .setRangDate(startDate, endDate)
            .setContentTextSize(18)
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .setLabel(
                "年",
                "月",
                "日",
                "",
                "",
                ""
            )
            .setLineSpacingMultiplier(3f)
            .setItemVisibleCount(3)
            .isDialog(false)
            .setOutSideCancelable(true)
            .setTextXOffset(0, 0, 0, 40, 0, -40)
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .build()
        pvCustomTime?.show()
    }

    private fun initCustomTime(adapterIndex: Int) {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        val selectedDate = Calendar.getInstance() //系统当前时间
        val startDate = Calendar.getInstance()
        startDate[1900, 0] = 1
        val endDate = Calendar.getInstance()
        endDate.add(Calendar.YEAR, +5)
//        endDate[2100, 2] = 28
        //时间选择器 ，自定义布局
        val pvCustomTime = TimePickerBuilder(
            this
        ) { date, v -> //选中事件回调
            val time = TimeUtils.date2String(date)
            myAppInfoAdapter.data[adapterIndex].text = time
            myAppInfoAdapter.notifyItemChanged(adapterIndex)
        }
            .setDate(selectedDate)
            .setRangDate(startDate, endDate)
            .setContentTextSize(18)
            .setType(booleanArrayOf(true, true, true, true, true, true))
            .setLabel(
                "年",
                "月",
                "日",
                "时",
                "分",
                "秒"
            )
            .setLineSpacingMultiplier(3f)
            .setItemVisibleCount(3)
            .isDialog(false)
            .setOutSideCancelable(true)
            .setTextXOffset(0, 0, 0, 40, 0, -40)
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .build()
        pvCustomTime?.show()
    }

    private fun initOptionsPicker(adapterIndex: Int) {

//        endDate[2100, 2] = 28
        //时间选择器 ，自定义布局
        val mOptionsPicker = OptionsPickerBuilder(
            this
        ) { option1, option2, option3, v ->
            myAppInfoAdapter.data[adapterIndex].text = viewModel.bkType[option1]
            myAppInfoAdapter.notifyItemChanged(adapterIndex)
        }
            .setContentTextSize(18)
            .setLineSpacingMultiplier(3f)
            .setItemVisibleCount(3)
            .isDialog(false)
            .setOutSideCancelable(true)
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .build<String>()
        mOptionsPicker?.setPicker(viewModel.bkType)
        mOptionsPicker?.show()
    }
}